# -*- coding: UTF-8 -*-

import sys

# Workaround to remove the reactor module created by PyInstaller twisted rthook.
# Otherwise you will get error
#   twisted.internet.error.ReactorAlreadyInstalledError: reactor already installed
if 'twisted.internet.reactor' in sys.modules:
    del sys.modules['twisted.internet.reactor']

from twisted.internet import selectreactor
selectreactor.install()

from twisted.internet import reactor, threads
from twisted.web import server as restfulServer

import time
from server_factory import *
import os
from logger import logger

from udp_server_factory import *

if NBIOT_ENABLE == 1:
    from restful_server_factory import *
    from twisted.internet import ssl
from storage import *

def main():

    storageTag = Storage()

    try:
        reactor.suggestThreadPoolSize(40)
        logger.info("-----------listenning port:%s--------------"%__port__)
        reactor.listenTCP(__port__, ServerFactory(storageTag))
        logger.info("-----------listenning UDP port:8609--------------")
        reactor.listenUDP(8609, UDPServerFactoryProtocol(storageTag))
        if NBIOT_ENABLE == 1:
            server = restfulServer.Site(NBIotServer(storageTag))
            if HTTPS_ENABLE == 0:
                reactor.listenTCP(8080, server)
            else:
                reactor.listenSSL(8080, server, ssl.DefaultOpenSSLContextFactory(
                'cert/server.key', 'cert/server.crt'))
        reactor.run()

    except Exception,e:
        logger.error(u"主线程出错，错误信息:{error}".format(error = traceback.format_exc()))

if __name__ == '__main__':
    try:
        __port__ = int(sys.argv[1])
    except:
        __port__ = 6800
    type = sys.getfilesystemencoding()
    main()